package uk.co.hs.web.initializer;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Class to control backend startup
 * Stripped out version of Alistairs TB version
 */
public class Controller
{
  private List<Controllable> mControllables;

  private static Comparator<Controllable> START_COMPARATOR = new Comparator<Controllable>()
  {
    public int compare(Controllable aO1,
                       Controllable aO2)
    {
      int result = 0;
      result = aO1.order() - aO2.order();
      return result;
    }
  };

  /**
   * Called on start
   */
  public void start()
  {
    Collections.sort(mControllables, START_COMPARATOR);
    for (Controllable cont : mControllables)
    {
      cont.start();
    }
  }

  /**
   * Called on shutdown
   */
  public void shutdown()
  {
    Collections.sort(mControllables, Collections.reverseOrder(START_COMPARATOR));
    for (Controllable cont : mControllables)
    {
      cont.shutdown();
    }
  }

  /**
   * Sets the list of controllables
   *
   * @param aControllables
   */
  public void setControllables(List<Controllable> aControllables)
  {
    mControllables = aControllables;
  }
}